package com.api.rocky.app;

import org.json.JSONArray;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.api.rocky.R;
import com.api.rocky.Data.Global;
import com.api.rocky.Util.Util;
import com.api.rocky.app.register.RegisterActivity;
import com.api.rocky.service.MyService;

public class LoginActivity extends Activity {
	
	private Context loginActivity;
	private LoginReceiver lrc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		if (Global.client != null) {
			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, ExampleActivity.class);
			startActivityForResult(intent, 1);
			finish();
		}else{
			setContentView(R.layout.activity_login);
			final EditText usernameEdit = (EditText) findViewById(R.id.edtuser);
			final EditText passwordEdit = (EditText) findViewById(R.id.edtpsd);
	
			Button loginButton = (Button) findViewById(R.id.login);
			loginButton.setOnClickListener(new Button.OnClickListener() {
	
				public void onClick(View arg0) {
					JSONArray jsa = new JSONArray();
					jsa.put(0);
					jsa.put(usernameEdit.getText().toString());
					jsa.put(passwordEdit.getText().toString());
					Util.SendMessageToServer(Global.client, jsa.toString());
					/*
					 * Intent intent = new Intent();
					 * intent.setClass(LoginActivity.this, ExampleActivity.class);
					 * startActivityForResult(intent, 1);
					 */
				}
			});
			Button registerButton = (Button) findViewById(R.id.register);
			registerButton.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, RegisterActivity.class);
					startActivityForResult(intent, 1);
				}
			});
			loginActivity = this;
			lrc = new LoginReceiver();
			startService(new Intent(loginActivity, MyService.class));
		}
    }
    
    

    @Override
	protected void onDestroy() {
		super.onDestroy();
	}



	@Override
	protected void onStart() {
		super.onStart();
		if(loginActivity != null){
			IntentFilter filter = new IntentFilter();
			filter.addAction("login");
			loginActivity.registerReceiver(lrc, filter);
		}
	}

    

	@Override
	protected void onStop() {
		super.onStop();
		if(loginActivity != null ) loginActivity.unregisterReceiver(lrc);
	}
    
    class LoginReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			String action = arg1.getAction();
			if(action.equals("login")){
				String msg = arg1.getStringExtra("msg");
				Toast.makeText(loginActivity, msg, Toast.LENGTH_SHORT).show();
				if(arg1.getBooleanExtra("status", false)){
					finish();
				}
			}
			
		}  
    	
    }
}
